<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="SwiftProtocol 在Swift中的Protocol不仅能定义方法还能定义属性,还可以配合Extension扩展使用,除了类可以遵循协议之外枚举,结构体也可以,’Protocol’中定义属性和方法,Protocol继承,聚合,关联类型,Swift标准库中常见的协议等等..">
<meta property="og:type" content="article">
<meta property="og:title" content="SwiftProtocol">
<meta property="og:url" content="http://yoursite.com/2018/06/20/SwiftProtocol/index.html">
<meta property="og:site_name" content="Erhqe">
<meta property="og:description" content="SwiftProtocol 在Swift中的Protocol不仅能定义方法还能定义属性,还可以配合Extension扩展使用,除了类可以遵循协议之外枚举,结构体也可以,’Protocol’中定义属性和方法,Protocol继承,聚合,关联类型,Swift标准库中常见的协议等等..">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-07-19T05:40:06.071Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SwiftProtocol">
<meta name="twitter:description" content="SwiftProtocol 在Swift中的Protocol不仅能定义方法还能定义属性,还可以配合Extension扩展使用,除了类可以遵循协议之外枚举,结构体也可以,’Protocol’中定义属性和方法,Protocol继承,聚合,关联类型,Swift标准库中常见的协议等等..">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/06/20/SwiftProtocol/"/>





  <title>SwiftProtocol | Erhqe</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Erhqe</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/06/20/SwiftProtocol/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Erhqe">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/10.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Erhqe">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SwiftProtocol</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-06-20T14:08:46+08:00">
                2018-06-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index">
                    <span itemprop="name">Swift</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/06/20/SwiftProtocol/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/06/20/SwiftProtocol/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="SwiftProtocol"><a href="#SwiftProtocol" class="headerlink" title="SwiftProtocol"></a>SwiftProtocol</h4><blockquote>
<p>在Swift中的<code>Protocol</code>不仅能定义方法还能定义属性,还可以配合<code>Extension</code>扩展使用,除了类可以遵循协议之外<code>枚举,结构体</code>也可以,’Protocol’中定义属性和方法,<code>Protocol继承,聚合,关联类型,Swift标准库中常见的协议等等..</code><a id="more"></a></p>
</blockquote>
<p> <code></code></p>
<h4 id="Protocol中定义属性和方法"><a href="#Protocol中定义属性和方法" class="headerlink" title="Protocol中定义属性和方法"></a>Protocol中定义属性和方法</h4><ul>
<li><p>Swift中的Protocol定义和定义枚举,结构体或者类的格式类似,使用<strong>Protocol</strong>关键字:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义一个名字为学生协议</span></span><br><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Student</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>协议中定义属性</strong></p>
<p>协议中定义属性表示遵循改协议的类型具备了某个属性,具体来说只能使用var关键字声明并且必须明确规定该属性是刻度的<code>get</code>还是可读可写<code>get set</code>,另外还可以通过关键字static声明一个类属性</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="comment">//定义一个可读可写的 name 属性</span></span><br><span class="line">    <span class="keyword">var</span> name: <span class="type">String</span> &#123; <span class="keyword">get</span> <span class="keyword">set</span> &#125;</span><br><span class="line">    <span class="comment">//定义一个可读的 birthPlace 属性</span></span><br><span class="line">    <span class="keyword">var</span> birthPlace: <span class="type">String</span> &#123; <span class="keyword">get</span> &#125;</span><br><span class="line">    <span class="comment">//定义一个类属性 record</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">var</span> qualification: <span class="type">String</span> &#123;<span class="keyword">get</span>&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>和定义方法一样,我们只需要确定该属性具体是什么类型并且添加对应的关键字,不需要具体的实现,更不能为他们赋上初始值(类似于计算属性)定义好属性之后,我们就可以利用属性来做点事情</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">PeopleStruct</span> : <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> name: <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">    <span class="keyword">var</span> birthPlace: <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">var</span> qualification: <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>定义一个<code>People</code>绝构体遵循<code>Student</code>协议,改结构体中必须存在协议要求声明的三个属性,对象属性如果在初始化方法中赋值,那么在定义后面可以不用赋值,如果没有必须赋值,而且类属性必输赋值,因为类属性通过类进行赋值所以,我们平时初始化之后得到的实例化对象并不能赋值,结构体会自动生成初始化方法:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> peopleStruct = <span class="type">PeopleStruct</span>(name: <span class="string">"name"</span>, birthPlace: <span class="string">"brithPlace"</span>)</span><br><span class="line"><span class="built_in">print</span>(peopleStruct.name)</span><br></pre></td></tr></table></figure>
<p>####类</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span>: <span class="title">Student</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> name: <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">    <span class="keyword">var</span> birthPlace: <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">var</span> qualification: <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">init</span>(name : <span class="type">String</span>, birthPlace : <span class="type">String</span>) &#123;</span><br><span class="line">        <span class="keyword">self</span>.name = name</span><br><span class="line">        <span class="keyword">self</span>.birthPlace = birthPlace</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> peopleClass = <span class="type">People</span>(name: <span class="string">"name1"</span>, birthPlace: <span class="string">"birthPlace1"</span>)</span><br><span class="line">peopleClass.birthPlace = <span class="string">"set"</span></span><br><span class="line"><span class="built_in">print</span>(peopleClass.birthPlace)</span><br></pre></td></tr></table></figure>
<p>发现在在<strong>Protocol</strong>中的<strong>birthPlace</strong>只有get方法没有set方法但是我们在上面可以修改,其实协议中的<strong>只读</strong>属性修饰的属性在协议这种类型的实例中为<strong>只读</strong></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 协议并不能结构体,类一样直接创建,但是可以利用赋值得到协议</span></span><br><span class="line"><span class="keyword">var</span> protocolStu : <span class="type">Student</span> = peopleClass</span><br><span class="line">protocolStu.birthPlace = <span class="string">"aa"</span></span><br><span class="line"><span class="comment">//Cannot assign to property: 'birthPlace' is a get-only property</span></span><br><span class="line"><span class="comment">//而且修改name不会报错</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>协议中定义方法</strong></p>
<p>和OC类似,Swift中的协议可以定义对类方法和对象方法,方法的参数不能有默认值(Swift认为默认值也是一种变相的实现)</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> name : <span class="type">String</span> &#123;<span class="keyword">get</span> <span class="keyword">set</span>&#125;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> <span class="title">stuby</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">mutating</span> <span class="function"><span class="keyword">func</span> <span class="title">changeName</span><span class="params">()</span></span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span>: <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> name : <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> <span class="title">stuby</span><span class="params">()</span></span> &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">changeName</span><span class="params">()</span></span> &#123;</span><br><span class="line">   		name = <span class="string">"ad"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">PeopleStruct</span> : <span class="title">Student</span> </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> name : <span class="type">String</span> = <span class="string">""</span></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> <span class="title">stuby</span><span class="params">()</span></span> &#123;</span><br><span class="line">    </span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">mutating</span> <span class="function"><span class="keyword">func</span> <span class="title">changeName</span><span class="params">()</span></span> &#123;</span><br><span class="line">       name = <span class="string">"ad"</span> </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> people = <span class="type">People</span>()</span><br><span class="line">people.changeName()</span><br><span class="line"><span class="type">People</span>.stuby()</span><br></pre></td></tr></table></figure>
<p>在上面发现函数前添加了<code>mutating</code>关键字,在结构体中协议函数实现中如果修改到了属性(包括协议属性,本身属性)那么函数前需要用<code>mutating</code>来修饰,在协议函数前也要修饰,而类不用</p>
</li>
<li><p><strong>协议中的初始化器</strong></p>
<p>我们可以在协议中定义遵循协议的类型需要实现指定的初始化器(构造函数)</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="keyword">init</span>(name : <span class="type">String</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span>: <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="keyword">required</span> <span class="keyword">init</span>(name: <span class="type">String</span>) &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">PeopleStruct</span> : <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="keyword">init</span>(name: <span class="type">String</span>) &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里我们看到了<code>required</code>关键字,我先了解一下<code>override</code></p>
<p><strong>override</strong>顾名思义当子类要覆盖父类的函数是需要用<strong><em>override</em></strong>修饰还需要调用父类的函数,将参数一并传递给父类函数:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> str:<span class="type">String</span></span><br><span class="line">    <span class="keyword">init</span>(str:<span class="type">String</span>) &#123;</span><br><span class="line">        <span class="keyword">self</span>.str = str</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MySubClass</span>:<span class="title">MyClass</span> </span>&#123;</span><br><span class="line">    <span class="keyword">override</span> <span class="keyword">init</span>(str:<span class="type">String</span>) &#123;</span><br><span class="line">        <span class="keyword">super</span>.<span class="keyword">init</span>(str:str)</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>required</strong>只能用于修饰类初<strong>始化方法</strong>,与<strong>override</strong>不同的是当子类含有变异初始化函数(参数名称不同、参数个数不同、参数类型不同)子类必须要实现父类的required初始化函数,并且也要使用required修饰符而不是override,当子类没有初始化函数时,可以不用实现父类的required初始化函数</p>
<p>也就是说如果父类的初始化方法<strong>required</strong>修饰的话:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Human</span> </span>&#123;</span><br><span class="line">   <span class="keyword">required</span> <span class="keyword">init</span>(age : <span class="type">Int</span>) &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span> : <span class="title">Human</span>  </span>&#123;</span><br><span class="line">     <span class="keyword">init</span>(name: <span class="type">String</span>) &#123;</span><br><span class="line">        <span class="keyword">super</span>.<span class="keyword">init</span>(age: <span class="number">1</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">required</span> <span class="keyword">init</span>(age: <span class="type">Int</span>) &#123;</span><br><span class="line">        <span class="built_in">fatalError</span>(<span class="string">"init(age:) has not been implemented"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所以<strong>protocol</strong>中指定初始化函数时,类遵循改<strong>Protocol</strong>会自动加上<strong>required</strong></p>
<p>而Struct则不会自动<strong>required</strong>,因为结构体没继承</p>
</li>
<li><p><strong>多个协议重名方法调用冲突</strong></p>
<p>如果某个类遵循了多个协议,而不同的协议中有相同名方法时,同时调用方法报错,而且自己看的都迷茫</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Student</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">()</span></span> -&gt;<span class="type">Int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Human</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">()</span></span> -&gt;<span class="type">String</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span> : <span class="title">Student</span> ,<span class="title">Human</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">()</span></span> -&gt;<span class="type">Int</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">10</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">()</span></span> -&gt;<span class="type">String</span> &#123;</span><br><span class="line">       <span class="keyword">return</span> <span class="string">"A"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//	解决方法</span></span><br><span class="line"><span class="keyword">let</span> p = <span class="type">People</span>(name: <span class="string">"a"</span>)</span><br><span class="line"><span class="number">_</span> = (p <span class="keyword">as</span> <span class="type">Student</span>).test()</span><br><span class="line"><span class="number">_</span> = (p <span class="keyword">as</span> <span class="type">Human</span>).test()</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="协议的继承-聚合-关联类型"><a href="#协议的继承-聚合-关联类型" class="headerlink" title="协议的继承,聚合,关联类型"></a>协议的继承,聚合,关联类型</h4><ul>
<li><p><strong>协议的继承</strong></p>
<p>官方文档说明:</p>
<blockquote>
<p>协议可以继承一个或多个其他协议并且可以在它继承的基础之上添加更多要求.协议继承的语法与类继承的语法相似.选择列出多个继承的协议.使用逗号分隔</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Student</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Human</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">manager</span> : <span class="title">Human</span> ,<span class="title">Student</span></span>&#123;&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>协议的聚合</strong></p>
<p>日常开发中要求一个类型同时遵守多个协议是很常见的.除了使用协议的继承外我们还可以使用如<code>Student &amp; Human</code>的形式实现<strong>协议聚合**</strong>(组合)**复合多个协议到一个要求里.例如:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typealias</span> compositionProtocol = <span class="type">Student</span> &amp; <span class="type">Human</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">(paramater : compositionProtocol)</span></span>&#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// people 遵守了上面两个协议</span></span><br><span class="line"><span class="keyword">let</span> people = <span class="type">People</span>()</span><br><span class="line">test(paramater: people)</span><br></pre></td></tr></table></figure>
<p>也可以使用Protocol继承来实现.区别就是一旦继承之后出现新的Protocol.如果我们只需要用一次的话我们还用继承是不是有点浪费了?.在这种情况下像上面这种方法好,这就是<strong>聚合</strong>.它并没有定义新的古亭协议类型.相反,它只是定义临时的拥有所有聚合中协议要求组成的局部协议</p>
</li>
<li><p><strong>协议的查验</strong></p>
<p>如何查验某各类是否遵守了特定的协议? : 使用关键字 <strong>is</strong>,同时该运算符返回一个Bool值用于判断条件是否成立</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> people = <span class="type">People</span>()</span><br><span class="line"><span class="keyword">if</span> (people <span class="keyword">is</span> <span class="type">Human</span>) &#123;</span><br><span class="line">	<span class="built_in">print</span>(<span class="string">"true"</span>)</span><br><span class="line">	&#125;</span><br><span class="line"><span class="comment">//	如果遵守了编译器也会提示 always true</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>关联类型</strong></p>
<p>协议的关联类型值的是根据使用场景的变化.如果协议中某些属性存在<strong>逻辑相同的而类型不同</strong>的情况,可以使用关键字<strong>associatedtype</strong>来为这些属性的类型声明<strong>关联类型</strong></p>
<p><strong>例如:</strong> 类Ruler (尺子)比如长度为Int来定义,类People身高用Float定义.类似有这种需求是可用<strong>关联类型</strong></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Attribute</span> </span>&#123;</span><br><span class="line">    associatedtype <span class="type">WidthType</span> <span class="comment">//	定义类型名称,比如系统Int类型</span></span><br><span class="line">    <span class="keyword">var</span> weight : <span class="type">WidthType</span> &#123;<span class="keyword">get</span>&#125; <span class="comment">// 定义遵守协议的类属性 </span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Ruler</span> : <span class="title">Attribute</span> </span>&#123;</span><br><span class="line">    <span class="keyword">typealias</span> <span class="type">WidthType</span> = <span class="type">Double</span>	<span class="comment">//重定义 WidthType的具体类型</span></span><br><span class="line">    <span class="keyword">var</span> weight : <span class="type">WidthType</span>	<span class="comment">// 实现协议中的属性</span></span><br><span class="line">    <span class="keyword">init</span>(weight : <span class="type">Double</span>) &#123;</span><br><span class="line">        <span class="keyword">self</span>.weight = weight</span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span> : <span class="title">Attribute</span>  </span>&#123;</span><br><span class="line">    <span class="keyword">typealias</span> <span class="type">WidthType</span> = <span class="type">Float</span></span><br><span class="line">    <span class="keyword">var</span> weight : <span class="type">WidthType</span></span><br><span class="line">    <span class="keyword">init</span>(height : <span class="type">Float</span>) &#123;</span><br><span class="line">        weight = height</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>协议扩展</strong></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Score</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> math: <span class="type">Int</span> &#123; <span class="keyword">get</span> <span class="keyword">set</span>&#125;</span><br><span class="line">    <span class="keyword">var</span> english: <span class="type">Int</span> &#123;<span class="keyword">get</span> <span class="keyword">set</span>&#125;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">mathPercent</span><span class="params">()</span></span> -&gt; <span class="type">Double</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">Score</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">mathPercent</span><span class="params">()</span></span> -&gt; <span class="type">Double</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="type">Double</span>(math) / <span class="type">Double</span>(math + english)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>原有类扩展</strong></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">Double</span> : <span class="title">CustomStringConvertible</span> </span>&#123;</span><br><span class="line">    <span class="comment">/// A textual representation of the value.</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">var</span> description: <span class="type">String</span> &#123; <span class="keyword">get</span> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/19/runtime/" rel="next" title="runtime">
                <i class="fa fa-chevron-left"></i> runtime
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/07/11/Quartz2D/" rel="prev" title="Quartz2D">
                Quartz2D <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/10.png"
                alt="Erhqe" />
            
              <p class="site-author-name" itemprop="name">Erhqe</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">31</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">tags</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#SwiftProtocol"><span class="nav-number">1.</span> <span class="nav-text">SwiftProtocol</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Protocol中定义属性和方法"><span class="nav-number">2.</span> <span class="nav-text">Protocol中定义属性和方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#协议的继承-聚合-关联类型"><span class="nav-number">3.</span> <span class="nav-text">协议的继承,聚合,关联类型</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Erhqe</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'TiAY2J24ECwQH9uLYsoJpgIK-gzGzoHsz',
        appKey: 'Y9PiVrPXVmfNsv4Aa6cPsADG',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
